package com.igeek.ch02.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebFilter(filterName = "/f2", urlPatterns = "/user/userViewAll.html")
public class LoginFilter implements Filter {

    public void init(FilterConfig config) throws ServletException {

    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        System.out.println("LoginFilter doFilter。。。");

        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;

        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");
        if(user==null){
            //未登录
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.println("<h2 style='color:red'>该资源必须登录后访问<a href='/user/userLogin.html'>请登录</a></h2>");
            out.flush();
            out.close();
            return;
        }

        //已登录，则通过过滤链，将处理后的请求、响应发至下一个过滤器或者目标资源
        chain.doFilter(request, response);
    }

    public void destroy() {

    }
}
